package uc

import (
	"bytes"
	"encoding/binary"
	log "github.com/sirupsen/logrus"
	"net"
)

var SendMap = make(map[uint32]net.Conn)
var ReceiveMap = make(map[uint32]net.Conn)

func handleTcpCon(conn net.Conn, receive chan Packet, bufferSize int32) {
	defer func() {
		if e := recover(); e != nil {
			log.Errorf("recover:%v", e)
		}
	}()
	var buffer = bytes.NewBuffer(make([]byte, 0, bufferSize)) //buffer用来缓存读取到的数据
	readBytes := make([]byte, bufferSize)                     //readBytes用来接收每次读取的数据，每次读取完成之后将readBytes添加到buffer中
	var packet = Packet{}
	for {
		//首先读取数据
		readByteNum, err := conn.Read(readBytes)
		if err != nil {
			log.Error(err)
			//conn.Close()
			return
		}
		buffer.Write(readBytes[0:readByteNum]) //将读取到的数据放到buffer中
		// 然后处理数据
		for {
			// body数据
			if packet.BodyLength != 0 && packet.Body == nil {
				if buffer.Len() >= int(packet.BodyLength) {
					bodyBytes := make([]byte, packet.BodyLength)
					_, err := buffer.Read(bodyBytes[:packet.BodyLength])
					if err != nil {
						log.Println(err)
					}
					packet.Body = bodyBytes
					//log.Println("Conn receive remote address:", conn.RemoteAddr(), "local address:", conn.LocalAddr(), "packetId:", packet.PacketId)
					newPacket := packet
					receive <- newPacket
					packet = Packet{}
					if buffer.Len() == 0 {
						buffer.Reset()
						break
					}
					// 读取的body长度不够
				} else {
					log.Println("bufferLen:", buffer.Len(), " < expect:", packet.BodyLength)
					break
				}
			}
			// header数据
			if packet.PacketId == 0 {
				if buffer.Len() >= 10 {
					header := buffer.Next(6)
					bodyLenBytes := buffer.Next(4)
					bodyLen := binary.BigEndian.Uint32(bodyLenBytes)
					// 第一次组装 header 及bodylength
					packet.ReqType = header[0]
					packet.PacketId = binary.BigEndian.Uint32(header[1:5])
					packet.PacketType = header[5]
					packet.BodyLength = bodyLen
					if receive == SendChan {
						SendMap[packet.PacketId] = conn
					} else if receive == ReceiveChan {
						ReceiveMap[packet.PacketId] = conn
					}
				} else {
					log.Println("header < 10, bufferLen:", buffer.Len())
					break
				}
			}
		}
	}
}

func HandleClientTcpCon(conn net.Conn, receive chan Packet, bufferSize int32) {
	handleTcpCon(conn, receive, 65536)
}

func HandleServerTcpCon(conn net.Conn, receive chan Packet) {
	handleTcpCon(conn, receive, 4096)
}
